﻿using System;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using XHD.BLL;
using XHD.Common;
using XHD.Controller;
using System.Text;

namespace XHD.Server
{
    public class BD_Warehouse
    {
        public static BLL.Crm_Warehouse wh = new BLL.Crm_Warehouse();
        public static BLL.Sys_log log = new BLL.Sys_log();
        public static BLL.Crm_Warehouse_KW kw = new BLL.Crm_Warehouse_KW();
       

        public static Model.Crm_Warehouse model = new Model.Crm_Warehouse();
        public static Model.Crm_Warehouse_KW modelkw = new Model.Crm_Warehouse_KW();

        public HttpContext Context;
        public string emp_id;
        public string emp_name;
        public Model.hr_employee employee;
        public HttpRequest request;
        public string uid;
        

        public BD_Warehouse()
        {
        }

        public BD_Warehouse(HttpContext context)
        {
            Context = context;
            request = context.Request;

            var userinfo = new User_info();
            employee = userinfo.GetCurrentEmpInfo(context);

            emp_id = employee.id;
            emp_name = PageValidate.InputText(employee.name, 50);
            uid = PageValidate.InputText(employee.uid, 50);
            
        }

        public string list()
        {
            int PageIndex = int.Parse(request["pageindex"] == null ? "1" : request["pageindex"]);
            int PageSize = int.Parse(request["pagesize"] == null ? "10" : request["pagesize"]);
            string sortname = request["sortname"];
            string sortorder = request["sortorder"];

            if (string.IsNullOrEmpty(sortname))
                sortname = " InDate ";
            if (string.IsNullOrEmpty(sortorder))
                sortorder = " desc";

            string sorttext = " " + sortname + " " + sortorder;

            string Total;
            string serchtxt = $"IsDel='N'";

            
            //if (!string.IsNullOrEmpty(request["cus_source_id"]))
            //    serchtxt += $" and cus_source_id =  '{PageValidate.InputText(request["cus_source_id"], 50)}'";

            //if (!string.IsNullOrEmpty(request["cus_industry_id"]))
            //    serchtxt += $" and cus_industry_id =  '{PageValidate.InputText(request["cus_industry_id"], 50)}'";


            DataSet ds = wh.GetList(PageSize, PageIndex, serchtxt, sorttext, out Total);
            string dt = GetGridJSON.DataTableToJSON1(ds.Tables[0], Total);

            return dt;


        }

        public string gridkw()
        {
            int PageIndex = int.Parse(request["pageindex"] == null ? "1" : request["pageindex"]);
            int PageSize = int.Parse(request["pagesize"] == null ? "10" : request["pagesize"]);
            string sortname = request["sortname"];
            string sortorder = request["sortorder"];

            if (string.IsNullOrEmpty(sortname))
                sortname = " w2.InDate ";
            if (string.IsNullOrEmpty(sortorder))
                sortorder = " desc";

            string sorttext = " " + sortname + " " + sortorder;

            string Total;
            string serchtxt = $" w2.IsDel='N'";


            //if (!string.IsNullOrEmpty(request["cus_source_id"]))
            //    serchtxt += $" and cus_source_id =  '{PageValidate.InputText(request["cus_source_id"], 50)}'";

            //if (!string.IsNullOrEmpty(request["cus_industry_id"]))
            //    serchtxt += $" and cus_industry_id =  '{PageValidate.InputText(request["cus_industry_id"], 50)}'";


            DataSet ds = kw.GetList(PageSize, PageIndex, serchtxt, sorttext, out Total);
            string dt = GetGridJSON.DataTableToJSON1(ds.Tables[0], Total);

            return dt;


        }

        public string formkw()
        {
            string KWID = PageValidate.InputText(request["KWID"], 50);
            string CkID = PageValidate.InputText(request["CkID"], 50);
            if ( (CkID==""&& KWID=="")||(CkID == "null"&& KWID == "null"))
                return "{}";

            DataSet ds = kw.GetList($" CkID = '{CkID}'  AND KWID='{KWID}'  and IsDel='N' ");
            return DataToJson.DataToJSON(ds);
        }

        public string form()
        {
            string id = PageValidate.InputText(request["id"], 50);

            if (!PageValidate.IsNumber(id))
                return "{}";

            DataSet ds = wh.GetList($" id = '{id}'  and IsDel='N' ");
            return DataToJson.DataToJSON(ds);
        }

        public string save()
        {
            string Name = PageValidate.InputText(request["Name"], 250);
            string sql = " SELECT * FROM dbo.Crm_Warehouse WHERE Name='"+ Name + "'";
      
            model.Name = Name;

            model.Address = PageValidate.InputText(request["Address"], 250);
            model.Lxr = PageValidate.InputText(request["lxr"], 250);
            string dh = PageValidate.InputText(request["lxrdh"], 250);
           
            model.Lxrdh = dh;
            model.Remark = PageValidate.InputText(request["Remark"], 250);
            model.InDate = DateTime.Now;
            model.IsDel = "N";
            model.DelEmpID = PageValidate.InputText(request["lxrid"], 250);

         
            //if (PageValidate.IsPhone(dh)) return XhdResult.Error("电话号码格式不对！").ToString();

            string id = PageValidate.InputText(request["id"], 50);
                if (PageValidate.IsNumber(id))
                {
                sql += " and ID!="+id+"";//修改的时候排除自己
                DataSet ds = DBUtility.DbHelperSQL.Query(sql.ToString());
                if (ds.Tables[0].Rows.Count > 0) return XhdResult.Error(Name + "《==名字有重复，请重新输入！").ToString();

                string sql1 = "  SELECT* FROM  dbo.Crm_Warehouse_KW WHERE CkID="+id+"";
                DataSet dss = DBUtility.DbHelperSQL.Query(sql1.ToString());
                if (dss.Tables[0].Rows.Count > 0) return XhdResult.Error(Name + "仓库已经维护库位，无法更新修改！").ToString();

                model.ID = int.Parse(id);
                    model.EditEmpID = emp_id;

                    bool isupdate = wh.Update(model);

                    if (!isupdate) return XhdResult.Error("更新失败！").ToString();

                    string logcontent = "";
                    //logcontent += Syslog.get_log_content(dr["isPrivate"].ToString(), request["isPrivate"], "公私", dr["isPrivate"].ToString() == "0" ? "私客" : "公客", request["isPrivate"]);

                    if (!string.IsNullOrEmpty(logcontent))
                    {
                        //日志

                        string UserID = emp_id;
                        string UserName = emp_name;
                        string IPStreet = request.UserHostAddress;
                        string EventTitle = model.Name;
                        string EventType = "[APP]仓库修改";
                        string EventID = model.ID.ToString();

                        Syslog.Add_log(UserID, UserName, IPStreet, EventTitle, EventType, EventID, logcontent);
                    }

                    return XhdResult.Success().ToString();
                }
                else
                {
                DataSet ds = DBUtility.DbHelperSQL.Query(sql.ToString());
                if (ds.Tables[0].Rows.Count > 0) return XhdResult.Error(Name + "《==名字有重复，请重新输入！").ToString();

                // id = Guid.NewGuid().ToString();
                //model.id = id;
                //model.in = emp_id.ToString();
                model.InDate = DateTime.Now;
                    model.InEmpID = emp_id;


                    var isadd = wh.Add(model);

                    if (isadd <= 0) return XhdResult.Error("添加失败！").ToString();
                
                return XhdResult.Success().ToString();
            }
            
        }

        public string savekw()
        {
            string Name = PageValidate.InputText(request["T_Name"], 250);
            string KWID= PageValidate.InputText(request["T_KW_name"], 250); 
            string CkID = PageValidate.InputText(request["T_category_parent_val"], 250);
           
            modelkw.Name = Name;
            modelkw.CkID = int.Parse( CkID);

            modelkw.Lxr = PageValidate.InputText(request["lxr"], 250);
            string dh = PageValidate.InputText(request["lxrdh"], 250);

            modelkw.Lxrdh = dh;
            modelkw.Remark = PageValidate.InputText(request["T_Remark"], 250);
            modelkw.InDate = DateTime.Now;
            modelkw.IsDel = "N";
            modelkw.DelEmpID = PageValidate.InputText(request["lxrid"], 250);


            //if (PageValidate.IsPhone(dh)) return XhdResult.Error("电话号码格式不对！").ToString();

             string kwid_ = PageValidate.InputText(request["KWID"], 50);//编辑状态传入的库位ID
            if (!string.IsNullOrEmpty(kwid_)&&kwid_!="null")
            {
               
                modelkw.KWID = kwid_;
                modelkw.EditEmpID = emp_id;

                bool isupdate = kw.Update(modelkw);

                if (!isupdate) return XhdResult.Error("更新失败！").ToString();

                string logcontent = "";
                //logcontent += Syslog.get_log_content(dr["isPrivate"].ToString(), request["isPrivate"], "公私", dr["isPrivate"].ToString() == "0" ? "私客" : "公客", request["isPrivate"]);

                if (!string.IsNullOrEmpty(logcontent))
                {
                    //日志

                    string UserID = emp_id;
                    string UserName = emp_name;
                    string IPStreet = request.UserHostAddress;
                    string EventTitle = model.Name;
                    string EventType = "[APP]库位修改";
                    string EventID = model.ID.ToString();

                    Syslog.Add_log(UserID, UserName, IPStreet, EventTitle, EventType, EventID, logcontent);
                }

                return XhdResult.Success().ToString();
            }
            else
            {
                string sql = " SELECT * FROM dbo.Crm_Warehouse_KW WHERE KWID='" + KWID + "' AND CkID=" + CkID + "";
                DataSet ds = DBUtility.DbHelperSQL.Query(sql.ToString());
                if (ds.Tables[0].Rows.Count > 0) return XhdResult.Error(Name + "【" + KWID + "】库位有重复，请重新输入！").ToString();

                // id = Guid.NewGuid().ToString();
                //model.id = id;
                //model.in = emp_id.ToString();
                modelkw.KWID = KWID;
                modelkw.InDate = DateTime.Now;
                modelkw.InEmpID = emp_id;


                var isadd = kw.Add(modelkw);

                if (!isadd) return XhdResult.Error("添加失败！").ToString();

                return XhdResult.Success().ToString();
            }

        }

        public string del(string id)
        {
             
            if (PageValidate.IsNumber(id))
            {
                string sql1 = "  SELECT* FROM  dbo.Crm_Warehouse_KW WHERE CkID=" + id + "";
                DataSet dss = DBUtility.DbHelperSQL.Query(sql1);
                if (dss.Tables[0].Rows.Count > 0) return XhdResult.Error( "仓库已经维护库位，无法删除！").ToString();


                if (wh.Delete(int.Parse( id)))
                    return XhdResult.Success().ToString();
                else return XhdResult.Error("删除错误！").ToString();
            }
                return XhdResult.Success().ToString();

    }

        public string delkw(string KWID, string CkID)
        {

            if (PageValidate.IsNumber(CkID))
            {

                if (kw.Delete(KWID, int.Parse(CkID)))
                    return XhdResult.Success().ToString();
                else return XhdResult.Error("删除错误！").ToString();
            }
            return XhdResult.Success().ToString();

        }
        public string combo()
        {
            string type = PageValidate.InputText(request["type"], 50);
            DataSet ds = GetList(type);

            StringBuilder str = new StringBuilder();

            str.Append("[");

            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                str.Append("{\"id\":\"" + ds.Tables[0].Rows[i]["ID"].ToString() + "\",\"text\":\"" + ds.Tables[0].Rows[i]["Name"] + "\"},");
            }
            str.Replace(",", "", str.Length - 1, 1);
            str.Append("]");
            return str.ToString();
        }
        public DataSet GetList(string type)
        {
            StringBuilder strSql = new StringBuilder();
            if (type == "CK")
                strSql.Append("SELECT   * FROM Crm_Warehouse	WHERE ISNULL(IsDel,'N')='N' ");
            else
                strSql.Append("SELECT   KWID AS ID,* FROM [dbo].[Crm_Warehouse_KW]	WHERE ISNULL(IsDel,'N')='N' AND CklbID=" + type);
            return DBUtility.DbHelperSQL.Query(strSql.ToString());
        }

        private string tojson(cusInfo ci)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("{");
            sb.Append($" \"log\":{ci.log},");
            sb.Append($"\"contact\":{ci.contact},");
            sb.Append($"\"follow\":{ci.follow},");
            sb.Append($"\"order\":{ci.order},");
            sb.Append($"\"receivable\":{ci.receivable}");
            sb.Append("}");

            return sb.ToString();
        }
 

       
    }

   
}
